package com.freely.component.activity;

import android.app.Activity;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;

public class FreelyActivityManager {
    private static List<AppCompatActivity> activities = new ArrayList<>();

    public static void add(@Nullable AppCompatActivity activity) {
        activities.add(activity);
    }

    public static void remove(@Nullable AppCompatActivity activity) {
        boolean destroyed = activity
                .getLifecycle()
                .getCurrentState()
                .isAtLeast(Lifecycle.State.DESTROYED);
        if (!destroyed) {
            activity.finish();
        }
        if (!activities.isEmpty()) {
            activities.remove(activity);
        }
    }

    public static void removeAll() {
        for (Activity activity : activities) {
            activity.finish();
        }
        activities.clear();
    }
}
